package com.cgsd.heyu.address;

import android.content.Context;
import android.content.res.AssetManager;

import com.apkfuns.logutils.LogUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.util.List;

public class GsonUtils {

    public static <T> List<T> getGsons(String json, Class<T> t) {
        Gson gson1 = new Gson();
        Type type = new TypeToken<List<T>>() {
        }.getType();
        List<T> list = null;
        try {
            list = gson1.fromJson(json, type);
        } catch (Exception e) {
        }
        return list;
    }

    public static <T> T getGson(String com, Class<T> t) {
        Gson gson = new Gson();
        T t1 = null;
        try {
            t1 = gson.fromJson(com, t);
        } catch (Exception e) {
            e.printStackTrace();
            LogUtils.e(""+e.getMessage());
        }
        return t1;
    }

    public static String toJson(Object t) {
        Gson gson = new Gson();
        return gson.toJson(t);
    }

    private static final String fileName = "region_address.json";

    /**
     * 读取本地 json文件
     * @param context
     * @return string
     */
    public static String getJsonToString(Context context) {
        StringBuilder builder = new StringBuilder();
        AssetManager assetManager = context.getAssets();
        //使用io读取文件
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(assetManager.open(fileName), "utf-8"));
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return builder.toString();
    }

}
